/* global FastClick: false, DISQUS: false, DISQUSWIDGETS: false, disqus_identifier:false, ga:false, Drawer: false, ImageLoader: false, NProgress: false, Prism: false */
(function ($, window, document, undefined) {

  'use strict';

  $(function () {

    // Cache a couple of useful elements
    // =================
    var $window   = $(window),
        $document = $(document),
        $html     = $(document.documentElement),
        $body     = $(document.body),
        $surface  = $body,
        $content  = $('.content', $surface),
        $backToTop = $('#back-to-top');

    // FastClick bindings
    // =================
    if (window.FastClick) {
      FastClick.attach(document.body);
    }

    // Drawer bindings
    // =================
    Drawer.init();

    // PrismJS handler
    // =================
    var _prismHandler;
    var Prism = window.Prism || null; //cm so I can test the prism plugin in ghost
    if(Prism){
      Prism.languages.js = Prism.languages.javascript;
      Prism.languages.html = Prism.languages.markup; // cm why? prism markup有对html的识别
      Prism.languages.text = Prism.languages.bash;
      Prism.languages.zsh = Prism.languages.bash;
      Prism.languages.vim = Prism.languages.text;
      _prismHandler = function() {
        $('code').not('[class*="language-"]').addClass(function() {
          var _lang = $(this).attr('class')  || 'markup';

          _lang = _lang.replace(/(language|lang)+\-/gi, '');
          return 'language-' + (Prism.languages.hasOwnProperty(_lang) ? _lang : 'markup');
        });
        var filenameTemp = '<div class="filename-holder">__name__</div>';

        $('code').filter('[class*=filename-]').attr('data-filename', function(){
          var $el = $(this);
          var classString = $el.attr('class');
          var pos = classString.search('filename-');
          var filename = ~pos ? classString.slice(pos, classString.indexOf(' ', pos)).split('-')[1] : false;
          $el.parent().before(filenameTemp.replace('__name__', filename)); // TODO 要不要在Prism高亮以后加一个wrapper？来放filename
          return filename;
        });

        Prism.highlightAll();
      };
    }else{
      Prism = {};
      _prismHandler = function(){
        console.log('No prism included');
      }
    }

    window.prismHandler = _prismHandler;
    $(document).ready(function(){
      _prismHandler();
    });

    // === gist
    var GistHandler = {
      process: function () {
        var $gistHolders = $('article .gist-holder')
        if($gistHolders.length){
          $gistHolders.each(function(index, holder){
            var $el = $(holder),
            gistId = $el.data('gistid'),
            filename = $el.data('gist-file') || '';
            if(!gistId){return}
            $.getGist(gistId, filename)
              .done(function(gist){
                $el.empty();
                var ordered = gist.ordered, len = ordered.length;
                for(var i = 0; i < len ; i++){
                  $el.append(ordered[i].content);
                }
              });
          });
        }
      }
    }

    $(document).ready(function(){
      // 暂时使用同步的就好...
      //GistHandler.process();
    });
    // === end gist


    // Data API bindings
    // =================
    $document.on('click', '[data-action]', function(e) {
      var _self = $(this),
         action = _self.data('action');

      var _openWindow = function(url, h, w) {
        var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left,
            dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top,
            left = ((screen.width / 2) - (w / 2)) + dualScreenLeft,
            top = ((screen.height / 2) - (h / 2)) + dualScreenTop;

        var newWindow = window.open(url, '',
          'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no' +
          ', width=' + w +
          ', height=' + h +
          ', top=' + top +
          ', left=' + left);

        // Puts focus on the newWindow
        if (window.focus) {
            newWindow.focus();
        }
        return newWindow;
      };

      e.preventDefault();

      switch(action) {
        case 'open-drawer':
          Drawer.open();
          break;
        case 'close-drawer':
          Drawer.close();
          break;
        case 'share-gplus':
          _openWindow(
            'https://plus.google.com/share?url=' + encodeURIComponent(location.href),
            600, 600);
          break;
        case 'share-facebook':
          _openWindow(
            'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(location.href),
            436, 626);
          break;
        case 'share-twitter':
          _openWindow(
            'https://twitter.com/share?url=' + encodeURIComponent(location.href) + '&text=' + encodeURIComponent(document.title),
            440, 550);
          break;
      }

      return false;
    });

    // Async load images
    $('[data-load-image]', $body).each(function() {
      ImageLoader.load($(this));
    });

    // Hide drawer button on scroll for best readability
    // =================
    $surface.on('scroll', function() {
      var offset = $surface.scrollTop(),
          btn = $('#drawer-button');
      if(offset === 0) {
        btn.removeClass('drawer-button-hidden');
      } else if(!btn.hasClass('drawer-button-hidden')) {
        btn.addClass('drawer-button-hidden');
      }
    });

    // Smooth scrolling for same page anchors
    // =================
    $document.on('click', 'a[href^=#]:not([href=#])', function(e) {
      e.preventDefault();

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $surface.animate({
          scrollTop: target.offset().top
        }, 500);
        location.hash = this.hash;
        return false;
      }
    });

    // Fix oveflow-scrolling on iOS7
    // =================
    $surface.on('touchstart', function(e) {});


    // 实现 scrolltop 的功能
    function scrollTo(pos){
      pos = (pos && pos.toString()) || '0';
      $body.animate({scrollTop: pos}, 800);
    }

    var scrollDelay = 200;
    var scrollTimeout = null;
    var scrollShowOffset = 400;
    $document
      .on('scroll', function(e){
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(function(){
          $document.trigger('scroll_end');
        },scrollDelay);
      })
      .on('scroll_end', function () {
        if($body.scrollTop() > scrollShowOffset){
          $backToTop.show().addClass('show');
          //$backToTop.fadeIn();
        }else{
          $backToTop.hide().removeClass('show');
          //$backToTop.fadeOut();
        }
      });

      $backToTop.on('click', function () {
        scrollTo(0);
      });

  });

  // TOC
  // =================
  TOC.init();

})($, window, document);
